<template>
    <div>
        <Header :title="title"></Header>
        <main>
            <div class="page">
                <van-form validate-first @submit="onSubmit">
                    <van-divider :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }">
                        基本信息
                    </van-divider>
                    <!-- 通过 pattern 进行正则校验 -->
                    <van-field v-model="pageData.createName" name="createName" placeholder="创建人" readonly
                        :rules="[{ required: true, message: '请输入创建人' }]" />
                    <!-- 通过 validator 进行函数校验 -->
                    <van-field v-model="pageData.createTime" name="createTime" placeholder="选择创建时间" label="时间"
                        :rules="[{ validator, message: '选择创建时间' }]">
                        <!-- #button 它是slot="button"的简写 -->
                        <template #button>
                            <van-button size="small" color="#6199ff" native-type='button' @click="showTime = true"
                                type="primary">选择时间</van-button>
                        </template>
                    </van-field>
                    <van-field v-model="pageData.projectName" name="projectName" placeholder="选择项目" label="项目"
                        :rules="[{ validator, message: '选择项目' }]">
                        <!-- #button 它是slot="button"的简写 -->
                        <template #button>
                            <van-button size="small" color="#6199ff" native-type='button' @click="projectShow = true"
                                type="primary">选择项目</van-button>
                        </template>
                    </van-field>
                    <van-divider :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }">
                        材料信息
                    </van-divider>
                    <van-field v-model="pageData.materialName" name="materialName" placeholder="选择材料" label="材料"
                        :rules="[{ validator, message: '选择材料' }]">
                        <!-- #button 它是slot="button"的简写 -->
                        <template #button>
                            <van-button size="small" color="#6199ff" native-type='button' @click="productShow = true"
                                type="primary">选择材料</van-button>
                        </template>
                    </van-field>
                    <van-field v-model="pageData.materialWeight" name="materialWeight" placeholder="数量" label="数量"
                        :rules="[{ required: true, message: '数量' }]" />
                    <van-field v-model="pageData.materialUnit" name="materialUnit" label="单位" placeholder="单位"
                        :rules="[{ required: true, message: '单位' }]" />
                    <van-field v-model="pageData.price" name="price" label="价格" placeholder="价格"
                        :rules="[{ required: true, message: '价格' }]" />
                    <van-divider :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }">
                        供应商信息
                    </van-divider>
                    <van-field v-model="pageData.supplierName" name="supplierName" label="供应商" placeholder="供应商"
                        :rules="[{ validator, message: '供应商' }]">
                        <!-- #button 它是slot="button"的简写 -->
                        <template #button>
                            <van-button size="small" color="#6199ff" @click="supplierShow = true" native-type='button'
                                type="primary">选择供应商</van-button>
                        </template>
                    </van-field>
                    <van-field v-model="pageData.supplierContact" name="supplierContact" label="联系人" placeholder="联系人"
                        :rules="[{ required: true, message: '联系人' }]" />
                    <van-field v-model="pageData.supplierPhone" name="supplierPhone" label="联系电话" placeholder="联系电话"
                        :rules="[{ required: true, message: '联系电话' }]" />


                    <van-divider :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }">
                        审批信息
                    </van-divider>
                    <van-field v-model="pageData.nextId" name="nextId" label="审批人" placeholder="审批人"
                        :rules="[{ validator, message: '审批人' }]">
                        <!-- #button 它是slot="button"的简写 -->
                        <template #button>
                            <van-button size="small" color="#6199ff" @click="userShow = true" native-type='button'
                                type="primary">选择审批人</van-button>
                        </template>
                    </van-field>
                    <van-field v-model="pageData.remark" name="remark" label="备注" rows="2" type="textarea"
                        maxlength="50" show-word-limit placeholder="备注" />

                    <van-button round block type="info" style="margin-top: 10px" color="#6199ff" native-type="submit">提交
                    </van-button>
                </van-form>
            </div>

            <!-- 所有的弹出框这样的组件一定不要放在表单内部 -->
            <van-calendar v-model="showTime" @confirm="timePickEvt" />

            <!-- 选择项目 -->
            <van-popup v-model="projectShow" position="right" :style="{ width: '90%', height: '100%' }">
                <div class="popup-list">
                    <input type="text" v-model="projectName" placeholder="输入供应商名字进行查询">
                    <ul>
                        <li @click="pickProjectEvt(it)" v-for="it in projectList" :key="it.id">
                            {{ it.name }}
                        </li>
                    </ul>
                </div>
            </van-popup>
            <!-- 选择供应商 -->
            <van-popup v-model="supplierShow" position="right" :style="{ width: '90%', height: '100%' }">
                <div class="popup-list">
                    <input type="text" v-model="supplierName" placeholder="输入供应商名字进行查询">
                    <ul>
                        <li @click="pickSupplierEvt(it)" v-for="it in supplierList" :key="it.id">
                            {{ it.name }}
                        </li>
                    </ul>
                </div>
            </van-popup>
            <!-- 选择供应商 -->
            <van-popup v-model="userShow" position="right" :style="{ width: '90%', height: '100%' }">
                <div class="popup-list">
                    <input type="text" v-model="userName" placeholder="输入供应商名字进行查询">
                    <ul>
                        <li @click="pickUserEvt(it)" v-for="it in userList" :key="it.id">
                            {{ it.name }}
                        </li>
                    </ul>
                </div>
            </van-popup>
            <!-- 选择项目 -->
            <van-popup v-model="productShow" position="right" :style="{ width: '90%', height: '100%' }">
                <div class="popup-list full">
                    <ul>
                        <li @click="pickProductEvt(it)" v-for="it in productList" :key="it.id">
                            {{ it.name }}
                        </li>
                    </ul>
                </div>
            </van-popup>
        </main>
    </div>
</template>
<script>
import moment from 'moment'
import { productInfoApi, productListApi, projectListApi, purchaseInfoApi, purchaseSaveApi, purchaseUpdateApi, supplierListApi, userListApi } from '@/api/homeApi'
import Header from '@/components/header.vue'

export default {
    data() {
        return {
            title: "编辑新增",
            // 页面的状态，是编辑、新增
            isEdit: false,
            showTime: false,
            projectShow: false,
            projectName: "",
            projectList: [],
            // 实现模糊查询的定时器
            projectTimer: null,
            productShow: false,
            productList: [],
            supplierName: "",
            supplierShow: false,
            supplierList: [],
            supplierTimer: null,
            userName: "",
            userShow: false,
            userList: [],
            userTimer: null,
            pattern: /\d{6}/,
            pageData: {
                nextId: "",
                createId: "",
                createName: "",
                createTime: "",
                projectId: "",
                projectName: "",
                materialId: "",
                materialName: "",
                materialUnit: "",
                materialWeight: "",
                price: "",
                supplierId: "",
                supplierName: "",
                supplierContact: "",
                supplierPhone: "",
                remark: ""
            }
        };
    },
    computed: {
        userInfo() {
            return this.$store.getters["common/userInfo"];
        }
    },
    watch: {
        projectShow(val) {
            if (val) {
                projectListApi({
                    name: this.projectName,
                    page: 1,
                    size: 50
                }).then(d => {
                    this.projectList = d.data.rows;
                });
            }
        },
        projectName() {
            clearTimeout(this.projectTimer);
            this.projectTimer = setTimeout(() => {
                projectListApi({
                    name: this.projectName,
                    page: 1,
                    size: 50
                }).then(d => {
                    this.projectList = d.data.rows;
                });
            }, 1500);
        },
        productShow(val) {
            if (val) {
                productListApi().then(d => {
                    this.productList = d.data.rows;
                });
            }
        },
        supplierShow(val) {
            if (val) {
                this.getSupplier();
            }
        },
        supplierName() {
            clearTimeout(this.supplierTimer);
            this.supplierTimer = setTimeout(() => {
                this.getSupplier();
            }, 1000);
        },
        userShow(val) {
            if (val) {
                this.getUser();
            }
        },
        userName() {
            clearTimeout(this.userTimer);
            this.userTimer = setTimeout(() => {
                this.getUser();
            }, 1000);
        }
    },
    created() {
        this.pageData.createId = this.userInfo.id;
        this.pageData.createName = this.userInfo.name;
        // 查看query参数，如果type === ‘edit'那么就表示是编辑数据
        // 设置标题，按钮
        // 需要获取详情信息，并赋值，这里一定要注意把remark赋空，nextId 要取第一个用户编码
        let query = this.$route.query;
        if (!!query && query.type === "edit") {
            this.isEdit = true;
            purchaseInfoApi(query.id).then(d => {
                this.pageData = {
                    ...d.data,
                    remark: "",
                    nextId: d.data.nextId[0] || ""
                };
            });
        }
    },
    methods: {
        getUser() {
            userListApi({
                name: this.userName,
                page: 1,
                size: 50
            }).then(d => {
                this.userList = d.data.rows;
            });
        },
        pickUserEvt(row) {
            this.pageData.nextId = row.id;
            this.userShow = false;
        },
        getSupplier() {
            supplierListApi({
                name: this.supplierName,
                page: 1,
                size: 50
            }).then(d => {
                this.supplierList = d.data.rows;
            });
        },
        pickSupplierEvt(row) {
            this.pageData.supplierId = row.id;
            this.pageData.supplierName = row.name;
            this.pageData.supplierContact = row.contact;
            this.pageData.supplierPhone = row.phone;
            this.supplierShow = false;
        },
        pickProductEvt(row) {
            this.pageData.materialId = row.id;
            this.pageData.materialName = row.name;
            this.productShow = false;
        },
        pickProjectEvt(row) {
            this.pageData.projectId = row.id;
            this.pageData.projectName = row.name;
            this.projectShow = false;
        },
        timePickEvt(date) {
            this.pageData.createTime = moment(date).format("yyyy-MM-DD");
            this.showTime = false;
        },
        validator(val) {
            return val.trim() !== "";
        },
        async onSubmit() {
            let obj = { ...this.pageData, nextId: [this.pageData.nextId] };
            let result;
            if (this.isEdit) {
                result = await purchaseUpdateApi(obj);
            }
            else {
                result = await purchaseSaveApi(obj);
            }
            if (result.code === 200) {
                this.$toast.success(`${this.isEdit ? "编辑" : "新增"}订单成功`);
                // 编辑以后，需要切换为新增
                this.isEdit = false;
                this.pageData = {
                    nextId: "",
                    createId: "",
                    createName: "",
                    createTime: "",
                    projectId: "",
                    projectName: "",
                    materialId: "",
                    materialName: "",
                    materialUnit: "",
                    materialWeight: "",
                    price: "",
                    supplierId: "",
                    supplierName: "",
                    supplierContact: "",
                    supplierPhone: "",
                    remark: ""
                };
            }
            else {
                this.$toast.fail(`${this.isEdit ? "编辑" : "新增"}订单失败`);
            }
        }
    },
    components: { Header }
}

</script>

<style lang="less" scoped>
.page {
    padding: 10px;
    display: block;
    height: calc(100% - 48px);
    overflow-x: hidden;
}

/deep/ .van-field__control {
    margin: 4px;
}
</style>